package org.example.forum.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.config.AppConfig;
import org.example.forum.model.Article;

import org.example.forum.model.ArticleReply;
import org.example.forum.model.User;
import org.example.forum.service.IArticleReplyService;
import org.example.forum.service.IArticleService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Autowired
    private IArticleReplyService articleReplyService;
    @Autowired
    private IArticleService articleService;
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,String content,Long articleId) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user == null||user.getId()<=0) {
            return AppResult.failed(ResultCode.ERROR_IS_NULL);
        }
        Article article=articleService.selectById(articleId);
       if(article==null) {
           log.warn("帖子不存在{}",articleId);
           return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
       }
       ArticleReply articleReply=new ArticleReply();
       articleReply.setContent(content);
       articleReply.setArticleId(articleId);
       articleReply.setPostUserId(user.getId());
       articleReply.setReplyUserId(article.getUserId());

        articleReplyService.create(articleReply);
       return AppResult.success();
    }
      @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getReplies(Long articleId) {
          Article article = articleService.selectById(articleId);
          if (article == null || article.getDeleteState() == 1) {
              // 返回错误提示
              return AppResult.failed(ResultCode.FAILED_NOT_EXISTS.toString());
          }
          // 调用Service
          List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
          // 返回结果
          return AppResult.success(articleReplies);
      }

}
